package wechat.app.getInterfaceCallCredentials;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import play.Logger;
import util.Common;
import util.DataFormatUtil;
import util.HttpUtil;
import util.cache.CacheUtil;

import java.io.InputStream;
import java.util.concurrent.Callable;

/**
 * Created by Administrator on 2016/3/7.
 */
public class AccessToken {
    /**
     * access_token是公众号的全局唯一票据，公众号调用各接口时都需使用access_token
     * 获取之后进行缓存，expires_in为有效时间，减少资源耗费
     * @param appKey 第三方用户唯一凭证
     * @param appSecret 第三方用户唯一凭证密钥
     * 正确返回{"access_token":"ACCESS_TOKEN","expires_in":7200}
     * 错误返回{"errcode":40013,"errmsg":"invalid appid"}
     * */
    public static String getAccessToken(final String appKey, final String appSecret) {
        final String cacheKey = "get_weixin_access_token_" + appKey + "_" + appSecret;
        Callable<String> fallback = new Callable<String>() {
            @Override
            public String call() throws Exception {
                String url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" + appKey + "&secret=" + appSecret;
                InputStream inputStream = HttpUtil.get(url);
                String res = DataFormatUtil.fullyReadStream(inputStream);
                // Logger.info(res);
                JSONObject resJson = JSON.parseObject(res);
                // TODO: 认证失败的情况
                if(resJson.containsKey("errcode")){
                    return null;
                }
                String accessToken = resJson.getString("access_token");
                int expiresIn = resJson.getInteger("expires_in");
                CacheUtil.set(cacheKey, accessToken, expiresIn);
                return accessToken;
            }
        };
        try {
            return CacheUtil.get(cacheKey, fallback);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
}
